var fs = require('fs');
var gulp = require('gulp');
var babel = require('gulp-babel');
var del = require('del');
var webpack = require('webpack');
var webpackDevServer = require('webpack-dev-server');
var port = 4000;


function webpackCompiler(config) {
    var compiler = webpack(config, function(err, stats) {
        if (err) {
            console.log(err);
        }else {
            console.log(stats.toString());
        }

    });
    compiler.plugin('done', stats => {
        console.log('done')
    });
}

gulp.task('clean', function(cb) {
    del(['dist']).then(function() {
        cb && cb();
    })
})

gulp.task('lib', function() {
    process.env.NODE_ENV = 'build';

    var babelConfig = require('./cfg/.babel.config.js');

    return gulp.src('src/**/*.js?(x)')
        .pipe(babel(babelConfig))
        .pipe(gulp.dest('lib'));
})

gulp.task('dev', function() {

    var config = require('./cfg/dev');

    var server = new webpackDevServer(webpack(config), {
        hot: true,
        contentBase: 'dist',
        disableHostCheck: true,
        host: '0.0.0.0'
    })
    
    server.listen(port, ()=> {
        console.log(`dev server listening on port ${port}`);
    });
})

gulp.task('build', ['clean'], function() {
    var config = require('./cfg/prod');
    webpackCompiler(config);
})


gulp.task('dll', function() {
    var config = require('./cfg/dllDev');
    webpackCompiler(config);
    var configProd = require('./cfg/dllProd')
    webpackCompiler(configProd);
})